var terrainClipPlan;

function TerrainexcavationOnload() {

    $("#Terrainexcavation_Excavation").click(function() {
        //绘制多边形
        Terrainexcavation_clear();
        tracker.trackPolygon(function(position) {
            var array = [].concat(position);
            var points = array;

            viewer.scene.globe.depthTestAgainstTerrain = true;
            var pointsLength = points.length;
            var pList = [];
            var terrainPList = [];
            var clippingPlanes = []; // 存储ClippingPlane集合
            for (var i = 0; i < pointsLength; ++i) {
                var nextIndex = (i + 1) % pointsLength;
                var midpoint = Cesium.Cartesian3.add(points[i], points[nextIndex], new Cesium.Cartesian3());
                midpoint = Cesium.Cartesian3.multiplyByScalar(midpoint, 0.5, midpoint);

                var up = Cesium.Cartesian3.normalize(midpoint, new Cesium.Cartesian3());
                var right = Cesium.Cartesian3.subtract(points[nextIndex], midpoint, new Cesium.Cartesian3());
                right = Cesium.Cartesian3.normalize(right, right);

                var normal = Cesium.Cartesian3.cross(right, up, new Cesium.Cartesian3());
                normal = Cesium.Cartesian3.normalize(normal, normal);

                var originCenteredPlane = new Cesium.Plane(normal, 0.0);
                var distance = Cesium.Plane.getPointDistance(originCenteredPlane, midpoint);

                clippingPlanes.push(new Cesium.ClippingPlane(normal, distance));
                var cartographic = Cesium.Cartographic.fromCartesian(array[i]);
                var longitude = Cesium.Math.toDegrees(cartographic.longitude);
                var latitude = Cesium.Math.toDegrees(cartographic.latitude);
                var h = cartographic.height;
                pList.push(longitude);
                pList.push(latitude);
                pList.push(h);
                terrainPList.push([longitude,latitude])
            }
            //TODO 根据地形服务获取当前坐标点高程值
            var terrainProvider = viewer.terrainProvider;
            if(terrainProvider){
                var pointArr = [];
                for(var j = 0 ; j < terrainPList.length ; j ++){
                    pointArr.push(Cesium.Cartographic.fromDegrees(terrainPList[j][0], terrainPList[j][1]));
                }
                var promise = Cesium.sampleTerrain(terrainProvider, 15, pointArr);
                Cesium.when(promise,function (updatedPositions) {
                    debugger
                    viewer.scene.globe.clippingPlanes = new Cesium.ClippingPlaneCollection({
                        planes: clippingPlanes,
                        edgeWidth: 1.0,
                        edgeColor: Cesium.Color.YELLOW.withAlpha(0)
                    });
                    if(updatedPositions && updatedPositions.length > 0){
                        var top = 0;
                        for (var i = 0 ; i < updatedPositions.length ; i ++){
                            top = updatedPositions[i].height > top ? updatedPositions[i].height : top;
                        }
                        top = top - parseFloat($('#depth').val());
                        for (var i = 0 ; i < updatedPositions.length ; i ++){
                            pList[i * 3 + 2] = top;
                        }
                    }
                    var s = viewer.entities.add({
                        polygon: {
                            hierarchy: Cesium.Cartesian3.fromDegreesArrayHeights(pList),
                            material: new Cesium.ImageMaterialProperty({
                                image: "img/excavate/excavate_side_min.jpg"
                            }),
                            closeTop: false, // 这个要设置为false
                            //extrudedHeight: parseFloat($('#depth').val()),
                            extrudedHeight: 0,
                            perPositionHeight: true // 这个要设置true
                        }
                    });
                },function (error) {
                    console.log(error);
                });
            }else{
                viewer.scene.globe.clippingPlanes = new Cesium.ClippingPlaneCollection({
                    planes: clippingPlanes,
                    edgeWidth: 1.0,
                    edgeColor: Cesium.Color.YELLOW
                });
            }
            // var list = [];
            // for (var i = 0, len = array.length; i < len; i++) {
            //     list.push(array[i]);
            //     var cartographic = Cesium.Cartographic.fromCartesian(array[i]);
            //     var longitude = Cesium.Math.toDegrees(cartographic.longitude);
            //     var latitude = Cesium.Math.toDegrees(cartographic.latitude);
            //     var h = cartographic.height;
            //     list[i].x = longitude;
            //     list[i].y = latitude;
            //     list[i].z = h;
            // }
            // viewer.entities.add({
            //     polygon: {
            //         hierarchy: new Cesium.PolygonHierarchy(list),
            //         material: new Cesium.ImageMaterialProperty({
            //             image: "img/excavate/excavate_side_min.jpg"
            //         }),
            //         closeTop: false, // 这个要设置为false
            //         extrudedHeight: 0,
            //         perPositionHeight: true // 这个要设置true
            //     }
            // });


            //开启深度检测
            // for (var i = 0, len = array.length; i < len; i++) {
            //     var cartographic = Cesium.Cartographic.fromCartesian(array[i]);
            //     var longitude = Cesium.Math.toDegrees(cartographic.longitude);
            //     var latitude = Cesium.Math.toDegrees(cartographic.latitude);
            //     var h = cartographic.height;
            //     array[i].x = longitude;
            //     array[i].y = latitude;
            //     array[i].z = h;
            // }
            // terrainClipPlan = new Cesium.TerrainClipPlan(viewer, {
            //     height: parseFloat($('#depth').val()),
            //     splitNum: parseFloat($('#depth').val()),
            //     wallImg: "img/excavate/excavate_side_min.jpg",
            //     bottomImg: "img/excavate/excavate_bottom_min.jpg"
            // });
            // terrainClipPlan.updateData(array)
        });
    })

    $("#Terrainexcavation_clear").click(function() {
        Terrainexcavation_clear();
    })

}

function Terrainexcavation_clear(clear) {
    terrainClipPlan && terrainClipPlan.clear();
    viewer.scene.globe.clippingPlanes = null;
    if (!clear) { removeAllEntities(); }
}